<template>
  <div id="update">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" class="inputWidth" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="昵称" class="inputWidth" prop="nickname">
        <el-input v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="密码" class="inputWidth" prop="password">
        <el-input type="password" v-model="ruleForm.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          round
          class="btn"
          @click="submitForm('ruleForm')"
          >确认添加</el-button
        >
        <el-button type="primary" round class="btn" @click="fn">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "Update",
  data() {
    return {
      ruleForm: {
        username: "",
        nickname: "",
        password: "",
      },

      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          // {
          //   min: 6,
          //   max: 18,
          //   message: "长度在 6 到 18 个字符",
          //   trigger: "blur",
          // },
          {
            pattern: /^[0-9A-Za-z]{6,18}$/,
            message: "长度为6-18位,不能包含非法字符",
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            pattern: /^[0-9A-Za-z]{1,8}$/,
            message: "长度为1-8位的字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^[0-9A-Za-z]{6,18}$/,
            message: "长度为6-18位,不能包含非法字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    console.log(this.$route.params.id);
  },
  methods: {
    ...mapActions(["update"]),
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        console.log(valid);
        let id = this.$route.params.id;
        let { username, nickname, password } = this.ruleForm;
        if (valid) {
          await this.update({ id, username, nickname, password });
          this.$router.history.go(-1);
        }
      });
    },
    fn() {
      this.$router.history.push("/users");
    },
  },
};
</script>

<style scope>
.inputWidth {
  width: 500px;
  margin: auto;
}
#useradd {
  text-align: center;
}
.btn {
  margin-top: 30px !important;
}
</style>